import json

from flask import Blueprint, request

# 设备类型
import sql

equipmentType = Blueprint('EquipmentTypeController', __name__)


# 获取所有设备类别信息
@equipmentType.route('/getEquipmentType')
def getEquipmentType():
    return '设备类型，拿到了'


# 添加设备类别信息
@equipmentType.route('/addEquipmentType', methods=['GET', 'POST'])
def addEquipmentType():
    req = json.loads(request.data)
    name = req['name']
    res = sql.add_type(name)

    if res > 0:
        print('add type %s success' % name)
        return 'success'
    else:
        return 'Fail.This name already exists in database.'


# 修改设备类别信息
@equipmentType.route('/updateEquipmentType', methods=['GET', 'POST'])
def updateEquipmentType():
    req = json.loads(request.data)
    name = req['name']
    t_id = req['id']
    res = sql.modify_type(t_id, name)

    if res > 0:
        print('modify type%s %s success' % (t_id, name))
        return 'success'
    else:
        return 'Fail.This name already exists in database.'


# 删除设备类别信息
@equipmentType.route('/deleteEquipmentType', methods=['GET', 'POST'])
def deleteEquipmentType():
    req = json.loads(request.data)
    t_id = req['id']
    res = sql.delete_type(t_id)

    if res > 0:
        print('delete type %s success' % t_id)
        return 'success'
    else:
        return 'Fail.This name already exists in database.'


# 增加绑定
@equipmentType.route('/addEquipmentConnection', methods=['GET', 'POST'])
def addConnection():
    req = json.loads(request.data)
    device_id = req['device_id']
    related_type = req['related_type']
    related_id = req['related_id']
    res = sql.add_connection(device_id, related_type, related_id)
    if res > 0:
        print('add connection for device%s success' % device_id)
        return 'success'
    else:
        return 'Fail.Such connection already exists! Please check your database. Add connection fail'


# 修改绑定
@equipmentType.route('/updateEquipmentConnection', methods=['GET', 'POST'])
def updateConnection():
    req = json.loads(request.data)
    c_id = req['id']
    device_id = req['device_id']
    related_type = req['related_type']
    related_id = req['related_id']
    res = sql.modify_connection(c_id, device_id, related_type, related_id)
    if res > 0:
        print('modify connection %s for device%s success' % (c_id, device_id))
        return 'success'
    else:
        return 'Fail.Such connection already exists! Please check your database. Modify connection fail'


# 删除绑定
@equipmentType.route('/deleteEquipmentConnection', methods=['GET', 'POST'])
def deleteConnection():
    req = json.loads(request.data)
    c_id = req['id']
    res = sql.delete_connection(c_id)
    if res > 0:
        print('delete connection %s' % c_id)
        return 'success'
    else:
        return 'Fail. Delete connection fail'
